#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
日志文件类
"""

import logging.handlers
import tornado.log
from logging.handlers import TimedRotatingFileHandler as RFHandler


levels = {"notset": logging.NOTSET,
          "debug": logging.DEBUG,
          "info": logging.INFO,
          "warn": logging.WARN,
          "error": logging.ERROR,
          "critical": logging.CRITICAL}


class LogFormatter(tornado.log.LogFormatter):

    def __init__(self, fmt='%(color)s[%(asctime)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s]%(end_color)s %('
                           'message)s'):
        super(LogFormatter, self).__init__(fmt=fmt, datefmt='%Y-%m-%d %H:%M:%S')


class Log_Handler(object):

    log_file_path = "logs/main_bill.log"

    fmt = '%(color)s[%(asctime)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s]%(end_color)s %(message)s'

    def __init__(self, logger, log_level="debug", log_file_path=log_file_path, backupCount=10, fmt=fmt):
        self.log_file_path = log_file_path
        self.backupCount = backupCount
        self.log_fmt = LogFormatter(fmt)
        self.log_level = log_level
        self.logger = logger

    def Timed_day_logger(self):
        """
        按天分割日志文件
        :return:
        """
        log_handler = RFHandler(filename=self.log_file_path, when="MIDNIGHT", encoding="utf-8", backupCount=self.backupCount)
        log_handler.setFormatter(self.log_fmt)
        self.logger.addHandler(log_handler)
        self.logger.setLevel(levels.get(self.log_level))
